const Koa = require("koa") ,
    KoaBodyParser = require("koa-bodyparser") ,
    KoaXML = require("koa-xml-body") ,
    util = require("util") ,
    { Middleware , EntityScaner }  = require("../../springbreeze/lib/index") 
    // EntityScaner = require("../../springbreeze/lib/util/EntityScaner") ,
    // { Middleware , EntityScaner } = require("../../springbreeze/lib/index")

/**
 *  提供Web服务的中间件
 *      该服务基于koa及相关生态组件构建,主要增加了自动加载action及一些常用的如
 *  权限，缓存等控制插件 
 *      
 *  配置项：
 *      port        端口,默认为9000
 *      actionPath  action的扫描跟目录,建议设置为绝对路径
 *      plugin      插件数组,按索引顺序加载
 *          name
 *          require 插件对象    
 *          .....   其他参数
 * 
 */
module.exports = class WebMiddleware extends Middleware {

    constructor( ){
        super()
        this.app = new Koa()
        this.app._Router = {}
    }

    before(){
        const app = this
        this.use( KoaXML() )
        this.use( KoaBodyParser() )

        this.use( async function( ctx , next ) {
            ctx.Kit = app.service()
            await next()
        })

        //加载插件模块
        //TEST 
        this.loadHandler()

        this.loadRouter()
    }

    async start(){
        const web = this
        const startPort = web.config().port || 9000  
        this.app.listen( startPort , async err => {
            if(err) throw err 
            Log.info( "App run at [%d]" , startPort  )
            web.after()
        })
    }

    use( fn ){
        this.app.use( fn )
    }

    loadPlugins(){
        //插件需要注入 this.app 对象，方便获取更多的配置
    }

    getRouter( key ){
        return this.router()[ key ]
    }

    router( r ){
        if( r ){
            Object.assign( this.app._Router , r )
        }
        return this.app._Router
    }

    loadRouter(){
        const path = this.config().actionPath || "action"
        Log.info("开始加载路由，扫描目录: [%s]" , path )
        const routerScaner = new EntityScaner()
        routerScaner.setNextPath( path )
        const routers = routerScaner.scan() 
        for( const index in routers ){
            const router =  routers[ index ] 
            if( router ){
                Log.info("-->加载路由[%s][%s]" , router.__nickname  , router.__path )
                this.app.use( router.koa() )
                //添加所有路由的配置
                this.router( router._route())
            }
        }
    }

    loadHandler(){
        const handlers = this.config().handler
        if( !handlers ) return 
        for( let idx in handlers ){
            const handler = handlers[ idx ]
            Log.info("--->加载插件[%s]完成" , handler.name )
            this.use( handler.entity )
        }
    }

}